package com.galina.notebook.dao.implementation;

import java.util.HashMap;
import java.util.Map;

import javax.ejb.EJB;
import javax.ejb.Stateless;
import javax.ejb.TransactionAttribute;
import javax.ejb.TransactionAttributeType;

import com.galina.notebook.dao.GenericDaoImpl;
import com.galina.notebook.dao.api.AccountDaoRemote;
import com.galina.notebook.dao.api.CommentDaoRemote;
import com.galina.notebook.dao.api.NoteDaoRemote;
import com.galina.notebook.persistence.Account;
import com.galina.notebook.persistence.Comment;
import com.galina.notebook.persistence.Note;

@Stateless
@TransactionAttribute(TransactionAttributeType.REQUIRED)
public class NoteDao extends GenericDaoImpl<Note> implements NoteDaoRemote {

	@EJB
	AccountDaoRemote accountDao;

	@EJB
	CommentDaoRemote commentDao;

	@Override
	public Note create(Note t) {
		Map<Comment, Account> manadgedMap = new HashMap<Comment, Account>();
		for (Comment comment : t.getComments().keySet()) {
			Comment manadgedComment = commentDao.find(comment.getId());
			Account account = t.getComments().get(comment);
			if (manadgedComment == null) {
				comment = commentDao.create(comment);
				manadgedComment = comment;
			}
			Account manadgedAccount = accountDao.find(account.getId());
			if (manadgedAccount == null) {
				account = accountDao.create(account);
				manadgedAccount = account;
			}
			manadgedMap.put(manadgedComment, manadgedAccount);
		}
		t.setComments(manadgedMap);
		return super.create(t);
	}

}